import { SocketUser } from "./SocketUser";
import { Project } from "./Entity/Common/Project";
import { IWebSocket } from "./IWebSocket";
import { Global } from "./Entity/Common/Global";
import { SendMsgTemplate } from "./Entity/SendMsgTemplate/SendMsgTemplate";
import { Queue } from "./Queue";
import { TaskTemplate } from "./Entity/Enum/TaskTemplate";

export class WebSocketHelper
{

    /** 项目信息 */
    private projectInfo:Project;

    /** 客户机 token */
    private clientToken:string;

    /** 服务token */
    private serviceToken:string;

    /** websocket 实例 */
    private ws:any;

    constructor(model:Project, ws:any)
    {
        var that = this;
        this.projectInfo = model;
        this.Authentication(model);
        this.ws = new ws(Global.WssService);
    }

    /** 验证身份 获取 ClientToken */
    private Authentication(model:Project)
    {
        var that = this;

        let socketUser = new SocketUser();

        socketUser
        .LoginWsByClient( model, (e) => {
            console.info(e)
            that.clientToken = e.info;
            that.ws.send("ixpe_userlogin:" + that.clientToken);
        });
    }

    send(msg:any,callback:Function = null, error:Function = null){

        var model:SendMsgTemplate = msg;

        model.ClientToken = this.clientToken;
        model.Template = "WebSocket";
        
        let queue = new Queue();
        queue.Push(msg,(e) => {
            if(e.code == 200)
            {
                callback && callback(e);
            }
            else{
                error && error(e.info);
            }

        },error);

    }

    onopen(event:Function){
        this.ws.onopen = event;
        this.ws.onopen(event);
    }

    onmessage(event:Function){
        this.ws.onmessage = event;
    }

    onclose(event:Function){
        this.ws.onclose = event;
    }

}